package com.zheng.umbrella.web.controller.manage;

/**
 * Created by Administrator on 2018/9/16.
 */

import com.zheng.common.base.BaseController;
import com.zheng.common.constant.Constant;
import com.zheng.common.util.UUIDUtil;
import com.zheng.umbrella.common.constant.UmbrellaConstant;
import com.zheng.umbrella.common.constant.UmbrellaResult;
import com.zheng.umbrella.common.constant.UmbrellaResultConstant;
import com.zheng.umbrella.dao.model.UmbrellaHardwareMachine;
import com.zheng.umbrella.dao.model.UmbrellaHardwareMachineExample;
import com.zheng.umbrella.dao.model.UmbrellaHardwarePath;
import com.zheng.umbrella.dao.model.UmbrellaHardwarePathExample;
import com.zheng.umbrella.rpc.api.UmbrellaHardwareApiService;
import com.zheng.umbrella.rpc.api.UmbrellaHardwareMachineService;
import com.zheng.umbrella.rpc.api.UmbrellaHardwarePathService;
import com.zheng.upms.dao.model.UpmsDict;
import com.zheng.upms.rpc.api.UpmsApiService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Administrator on 2018/9/16.
 */
@Controller
@Api(value = "伞道管理", description = "伞道管理")
@RequestMapping("/manage/path")
public class UmbrellaHardwarePathController  extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UmbrellaHardwarePathController.class);

    @Autowired
    private UmbrellaHardwarePathService umbrellaHardwarePathService;

    @Autowired
    private UmbrellaHardwareApiService umbrellaHardwareApiService;

    @Autowired
    private UmbrellaHardwareMachineService umbrellaHardwareMachineService;

    @Autowired
    private UpmsApiService upmsApiService;

    @ApiOperation(value = "伞道首页")
    @RequiresPermissions("umbrella:path:read")
    @RequestMapping(value = "/index", method = {RequestMethod.GET, RequestMethod.POST})
    public String index() {
        return "/manage/path/index.jsp";
    }

    @ApiOperation(value = "伞道列表")
    @RequiresPermissions("umbrella:path:read")
    @RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object list(
            @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
            @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
            @RequestParam(required = false, defaultValue = "", value = "search") String search,
            @RequestParam(required = false, value = "sort") String sort,
            @RequestParam(required = false, value = "order") String order,
            @RequestParam(required = false, value = "machineCode") String machineCode) {
        String userName = getLoginUserName();
        Integer agentId = upmsApiService.selectUserAgentIdByUsername(userName);
        UmbrellaHardwarePathExample umbrellaHardwarePathExample = new UmbrellaHardwarePathExample();
        UmbrellaHardwarePathExample.Criteria criteria = umbrellaHardwarePathExample.createCriteria();
        criteria.andFlagEqualTo(Constant.CONST_FLAG_NORMAL);

        //代理数据限制
        if(agentId!=null && agentId!=Constant.CONST_SUPER_AGENTID){
            criteria.andAgentIdEqualTo(agentId);
        }
        //System.out.println(criteria.toString());
        if (StringUtils.isNotBlank(machineCode)) {
            criteria.andMachineCodeEqualTo(machineCode);
        }
        if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) {
            umbrellaHardwarePathExample.setOrderByClause(sort + " " + order);
        }
        if (StringUtils.isNotBlank(search)) {
            criteria.andCodeLike("%" + search + "%");
        }
        List<UmbrellaHardwarePath> rows = umbrellaHardwarePathService.selectByExampleForOffsetPage(umbrellaHardwarePathExample, offset, limit);
        long total = umbrellaHardwarePathService.countByExample(umbrellaHardwarePathExample);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", rows);
        result.put("total", total);
        return result;
    }

    @ApiOperation(value = "新增伞道")
    @RequiresPermissions("umbrella:path:create")
    @RequestMapping(value = "/create", method = {RequestMethod.GET})
    public String create(ModelMap modelMap) {
        String loginUserName = getLoginUserName();
        UmbrellaHardwareMachineExample machineExample = new UmbrellaHardwareMachineExample();
        machineExample.createCriteria().andFlagEqualTo(Constant.CONST_FLAG_NORMAL)
                .andAgentIdEqualTo(upmsApiService.selectUserAgentIdByUsername(loginUserName));
        List<UmbrellaHardwareMachine> umbrellaHardwareMachineList = umbrellaHardwareApiService.selectMachineByExample(machineExample);
        modelMap.put("machineList", umbrellaHardwareMachineList);
        //伞道类型
        List<UpmsDict> typeList = upmsApiService.selectUpmsDictByCode(UmbrellaConstant.UM_MACHINE_PATH_TYPE);
        modelMap.put("typeList", typeList);

        UmbrellaHardwarePath umbrellaHardwarePath = new UmbrellaHardwarePath();
        umbrellaHardwarePath.setCode(UUIDUtil.get32UUID());
        modelMap.put("umbrellaHardwarePath", umbrellaHardwarePath);
        return "/manage/path/create.jsp";
    }

    @ApiOperation(value = "新增伞道")
    @RequiresPermissions("umbrella:path:create")
    @ResponseBody
    @RequestMapping(value = "/create", method = {RequestMethod.POST})
    public Object create(UmbrellaHardwarePath umbrellaHardwarePath) {
//        ComplexResult result = FluentValidator.checkAll()
//                .on(upmsAgent.getName(), new LengthValidator(1, 120, "名称"))
//                .doValidate()
//                .result(ResultCollectors.toComplex());
//        if (!result.isSuccess()) {
//            return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors());
//        }
        int machintPathCount = 0;
        int hasPathCount = 0;
        UmbrellaHardwareMachineExample machineExample = new UmbrellaHardwareMachineExample();
        machineExample.createCriteria().andFlagEqualTo(Constant.CONST_FLAG_NORMAL).andCodeEqualTo(umbrellaHardwarePath.getMachineCode());
        UmbrellaHardwareMachine machine = umbrellaHardwareMachineService.selectFirstByExample(machineExample);
        if(machine!=null){
            machintPathCount = machine.getPathcount();
        }
        UmbrellaHardwarePathExample pathExample = new UmbrellaHardwarePathExample();
        pathExample.createCriteria().andFlagEqualTo(Constant.CONST_FLAG_NORMAL).andMachineCodeEqualTo(umbrellaHardwarePath.getMachineCode());
        List<UmbrellaHardwarePath> pathList = umbrellaHardwarePathService.selectByExample(pathExample);
        if(pathList!=null && pathList.size()>0){
            hasPathCount = pathList.size();
        }
        if ( (hasPathCount + 1) > machintPathCount ){
            return new UmbrellaResult(UmbrellaResultConstant.FAILED, "伞道数量不可超过伞机伞道额定数量。");
        }
        String loginUserName = getLoginUserName();
        long time = System.currentTimeMillis();
        umbrellaHardwarePath.setAgentId(upmsApiService.selectUserAgentIdByUsername(loginUserName));
        umbrellaHardwarePath.setCtime(time);
        umbrellaHardwarePath.setCuser(getLoginUserName());
        int count = umbrellaHardwarePathService.insertSelective(umbrellaHardwarePath);
        return new UmbrellaResult(UmbrellaResultConstant.SUCCESS, count);
    }

    @ApiOperation(value = "删除伞道")
    @RequiresPermissions("umbrella:path:delete")
    @RequestMapping(value = "/delete/{ids}",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object delete(@PathVariable("ids") String ids) {
//        int count = umbrellaHardwarePathService.deleteByPrimaryKeys(ids);
        int count = umbrellaHardwarePathService.deleteLogicByPrimaryKeys(ids,UmbrellaHardwarePath.class,null);
        return new UmbrellaResult(UmbrellaResultConstant.SUCCESS, count);
    }

    @ApiOperation(value = "修改伞道")
    @RequiresPermissions("umbrella:path:update")
    @RequestMapping(value = "/update/{id}", method = {RequestMethod.GET})
    public String update(@PathVariable("id") int id, ModelMap modelMap) {
        String loginUserName = getLoginUserName();
        UmbrellaHardwareMachineExample machineExample = new UmbrellaHardwareMachineExample();
        machineExample.createCriteria().andFlagEqualTo(Constant.CONST_FLAG_NORMAL)
                .andAgentIdEqualTo(upmsApiService.selectUserAgentIdByUsername(loginUserName));
        List<UmbrellaHardwareMachine> umbrellaHardwareMachineList = umbrellaHardwareApiService.selectMachineByExample(machineExample);
        modelMap.put("machineList", umbrellaHardwareMachineList);
        //伞道类型
        List<UpmsDict> typeList = upmsApiService.selectUpmsDictByCode(UmbrellaConstant.UM_MACHINE_PATH_TYPE);
        modelMap.put("typeList", typeList);

        UmbrellaHardwarePath umbrellaHardwarePath = umbrellaHardwarePathService.selectByPrimaryKey(id);
        modelMap.put("umbrellaHardwarePath", umbrellaHardwarePath);
        return "/manage/path/update.jsp";
    }

    @ApiOperation(value = "修改伞道")
    @RequiresPermissions("umbrella:path:update")
    @RequestMapping(value = "/update/{id}", method = {RequestMethod.POST})
    @ResponseBody
    public Object update(@PathVariable("id") Integer id, UmbrellaHardwarePath umbrellaHardwarePath) {
//        ComplexResult result = FluentValidator.checkAll()
//                .on(upmsAgent.getName(), new LengthValidator(1, 20, "名称"))
//                .doValidate()
//                .result(ResultCollectors.toComplex());
//        if (!result.isSuccess()) {
//            return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors());
//        }
        umbrellaHardwarePath.setId(id);
        int count = umbrellaHardwarePathService.updateByPrimaryKeySelective(umbrellaHardwarePath);
        return new UmbrellaResult(UmbrellaResultConstant.SUCCESS, count);
    }


}
